package com.siki.controller.file;

import com.siki.config.jsonConfig.JsonResult;
import com.siki.utils.fileUtils.FileNameUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Author Siki
 * @Date 2020/4/22
 */
@Api(tags = "[文件处理相关接口]")
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    //上传的路径,一般是放在访问路径，比如http://sikic.cn/img/javawork
    //后面的/img/javawork就是path
    @Value("${siki-path}")
    private String PATH;

    @Value("${new-siki-path}")
    private String NEW_PATH; //新文件路径，下载文件才用

    @ApiOperation(value = "[文件] - 上传文件", httpMethod = "POST", consumes = "application/form-data")
    @PostMapping(value = "/upload")
    public JsonResult upload(@RequestParam MultipartFile file){
        String fileName = file.getOriginalFilename();
        String newFileName = FileNameUtils.getFileName(fileName);

        // 生成新的文件名
        String realPath = PATH + "/" + newFileName;
        File dest = new File(realPath);

        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try {
            //保存文件
            file.transferTo(dest);
            return JsonResult.success(NEW_PATH+"/"+newFileName);
        } catch (IOException e) {
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "[文件] - 下载文件", httpMethod = "GET", consumes = "application/form-data")
    @GetMapping(value = "/download/{filename}")
    public JsonResult download(HttpServletResponse response, @ApiParam("文件名称") @PathVariable("filename") String fileName){
        File file = new File(PATH +'/'+ fileName);
        if(!file.exists()){
            return JsonResult.fail("文件不存在");
        }
        response.reset();
//        response.setContentType("application/form-data");
//        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName );

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.success("下载成功");
    }


}


